﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SmartChess
{
    class InteractiveBrain : Brain
    {
        protected TaskCompletionSource<ChessMove> _selectorTcs;

        public override Task<ChessMove> SelectMoveAsync(Game game, int player)
        {
            if (_selectorTcs != null)
                throw new InvalidOperationException("Can only wait for one move.");

            _selectorTcs = new TaskCompletionSource<ChessMove>();
            return _selectorTcs.Task;
        }
        public override void Detach(IMoveSelector selector)
        {
            selector.MoveSelected -= MoveSelected;
        }
        public override void Attach(IMoveSelector selector)
        {
            selector.MoveSelected += MoveSelected;
        }
        public void MoveSelected(object sender, MoveSelectedEventArgs e)
        {
            Console.WriteLine("Move gewählt: " + e.Move.PlayerId);
            if (_selectorTcs != null)
            {
                _selectorTcs.SetResult(e.Move);
                _selectorTcs = null;
            }
        }
    }
    public delegate void MoveSelectEventHandler(object sender, MoveSelectedEventArgs e);
    public interface IMoveSelector
    {
        event MoveSelectEventHandler MoveSelected;
    }
    public class MoveSelectedEventArgs : EventArgs
    {
        public ChessMove Move { get; private set; }
        public MoveSelectedEventArgs(ChessMove move)
        {
            Move = move;
        }
    }
}
